package com.gf.pokemon.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.gf.pokemon.constants.OAGroup;
import com.gf.pokemon.dto.LoginUser;
import com.gf.pokemon.mapper.AuserMapper;
import com.gf.pokemon.platform.utils.LoginUserHelper;
import com.gf.pokemon.remote.oa.OaService;

@Service
public class AuserService {
	
	@Resource
	private AuserMapper auserMapper;
	
	private final String SPLIT_SIGN = ";";
	
	private final String flowName = "统计";
	
	@Resource
	private OaService oaService;
	
	/**
	 * 发送OA流程请求
	 * @param title   标题
	 * @param userStr 用户str，需要解析
	 * @param url	  oa跳转url
	 * @param unique  唯一编号
	 */
	public void sendCreateOARequest(String title,String userStr,String url,String unique){
		List<String> userIds = this.getOAUser(userStr);
		if(CollectionUtils.isEmpty(userIds)){
			return;
		}
		LoginUser user = LoginUserHelper.getLoginUser();
		oaService.pushOA(flowName, flowName, title, user.getName(), userIds, unique, url);
	}
	
	/**
	 * 关闭OA流程
	 * @param user
	 * @param unique
	 */
	public void sendCloseOARequest(String user,String unique){
		oaService.closeOA(flowName, flowName, user, unique);
	}
	
	

	/**
	 * 解析输入获取用户OA账户集合
	 * @param userStr
	 * @return
	 */
	public List<String> getOAUser(String userStr){
		List<String> oaUser = new ArrayList<String>();
		if(StringUtils.isBlank(userStr)){
			return oaUser;
		}
		
		List<String> oriUserStrs = Arrays.asList(userStr.split(SPLIT_SIGN));
		for(String oriUserStr:oriUserStrs){
			OAGroup oaGroup = OAGroup.parseName(oriUserStr);
			//无法解析就当成真实的OA账号
			if(oaGroup==null){
				oaUser.add(oriUserStr);
			}
			else{
				oaUser.addAll(getOAUserByGroup(oaGroup));
			}
		}
		return oaUser;
	}
	
	/**
	 * 根据oaGroup对象获取用户的OA账户
	 * @param oaGroup
	 * @return
	 */
	public List<String> getOAUserByGroup(OAGroup oaGroup){
		if(oaGroup==null){
			return new ArrayList<String>();
		}
		List<String> orgIds = new ArrayList<String>();
		if(oaGroup.isParent()){
			orgIds.addAll(auserMapper.getOidByParentId(oaGroup.getOrgId()));
		}else{
			orgIds.add(oaGroup.getOrgId());
		}
		return auserMapper.getUserIdByOid(orgIds);
	}
	
	public AuserMapper getAuserMapper() {
		return auserMapper;
	}

	public void setAuserMapper(AuserMapper auserMapper) {
		this.auserMapper = auserMapper;
	}
	
}
